﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using logic;
using DAL;
using Newtonsoft.Json;
using System.Data;
using System.Text;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using System.IO;
using NPOI.HSSF.Util;
using Facade.Excel;

namespace PeisongWeb.admin
{
    public partial class buyerPriceWeekEdit : adminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("KB", 1))
                {
                    getDetails();
                    BindSelectedProduct();
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                    return;
                }
            }
        }

        public int bpwdid
        {
            get
            {
                int id = 0;
                int.TryParse(Request.QueryString["bpwid"], out id);
                return id;
            }
        }

        public int companyId
        {
            get
            {
                if (ViewState["companyId"] != null)
                {
                    return Convert.ToInt32(ViewState["companyId"]);
                }
                return 0;
            }
            set
            {
                ViewState["companyId"] = value;
            }
        }

        private void getDetails()
        {
            PurchaseWeekEntity buyerPriceWeek = logic.purchaseWeek.getById(bpwdid);
            lblCompany.Text = logic.company.getById(buyerPriceWeek.CompanyId).Company;
            lblWeek.Text = string.Format("第{0}周", buyerPriceWeek.Week);
            lblStartTime.Text = buyerPriceWeek.StartTime.ToLongDateString();
            lblEndTime.Text = buyerPriceWeek.EndTime.ToLongDateString();
            lblCreateAdmin.Text = logic.sysAdmin.getById(buyerPriceWeek.CreateAdminId).Username;
            lblAuditAdmin.Text = logic.sysAdmin.getById(buyerPriceWeek.AuditAdminId).Username;

            if (DateTime.MinValue != buyerPriceWeek.InputDt)
            {
                lblCreateDt.Text = buyerPriceWeek.InputDt.ToLongDateString();
            }

            if(DateTime.MinValue!=buyerPriceWeek.UpdatestatusDt)
            {
                lblAuditDt.Text = buyerPriceWeek.UpdatestatusDt.ToLongDateString();
            }

            if (buyerPriceWeek.UpdatestatusDt != DateTime.MinValue && buyerPriceWeek.AuditAdminId != 0 && buyerPriceWeek.Status == "2")
            {
                btnAudit.Enabled = false;
            }
            else
            {
                btnAudit.Enabled = true;
            }

            if (buyerPriceWeek.UpdatestatusDt != DateTime.MinValue)
            {
                lblAuditDt.Text = buyerPriceWeek.UpdatestatusDt.ToString();
            }
            companyId = buyerPriceWeek.CompanyId;

            if (!string.IsNullOrEmpty(Request.QueryString["action"]) && Request.QueryString["action"] == "edit")
            {
                // 绑定周价商品
                DataTable dt = logic.buyerWeeklyPrice.listWithCompanyWeek(bpwdid);
                List<WeeklyProductItem> items = new List<WeeklyProductItem>();

                WeeklyProductItem product = null;

                foreach (DataRow row in dt.Rows)
                {
                    product = new WeeklyProductItem()
                    {
                        ProductId = Convert.ToInt32(row["productId"]),
                        ProductName = row["name"].ToString(),
                        AutoAdd = Convert.ToDecimal(row["initPriceRate"]),
                        AvgSellerPrice = Convert.ToDecimal(row["avgSellerPrice"]),
                        Price = Convert.ToDecimal(row["avgSellerPrice"]) * (1 + Convert.ToDecimal(row["priceRate"]))
                    };
                    items.Add(product);
                }

                hdProductSotre.Value = JsonConvert.SerializeObject(items);
            }
        }

        #region 弹出窗口数据 绑定

        void categoryRootBind()
        {
            ddl_CategoryRoot.DataSource = logic.category.listWithCompanyRange(companyId);
            ddl_CategoryRoot.DataBind();
            ddl_CategoryRoot.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
        }

        void categorySubBind()
        {
            //当大类不等于空的时候，就绑定小类
            if (ddl_CategoryRoot.SelectedValue != "")
            {
                DataTable dt = logic.category.getByParent(Convert.ToInt32(ddl_CategoryRoot.SelectedValue));
                ddl_CategorySub.DataSource = dt;
                ddl_CategorySub.DataBind();
                ddl_CategorySub.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
            }
            else
            {
                ddl_CategorySub.Items.Clear();
                ddl_CategorySub.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
            }
        }

        protected void ddl_CategoryRoot_SelectedIndexChanged(object sender, EventArgs e)
        {
            categorySubBind();
        }

        protected void BindAllProducts()
        {
            StringBuilder where = new StringBuilder();

            if (!string.IsNullOrEmpty(ddl_CategorySub.SelectedValue))
                where.AppendFormat(" and a.categoryId={0}", ddl_CategorySub.SelectedValue);
            if (txt_ProductNo.Text.Trim() != "")
                where.AppendFormat(" and a.productNo='{0}'", txt_ProductNo.Text.Trim());
            if (txt_ProductName.Text.Trim() != "")
                where.AppendFormat(" and a.[name] like '%{0}%'", txt_ProductName.Text.Trim());

            DataSet ds = logic.buyerWeeklyPrice.listWithAvgSellerPrice(bpwdid, where.ToString(), AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize);
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);

            rpt_Products.DataSource = ds.Tables[1];
            rpt_Products.DataBind();


        }

        // 搜索
        protected void lbn_search_Click(object sender, EventArgs e)
        {
            BindAllProducts();
        }

        // 重置
        protected void lbn_reset_Click(object sender, EventArgs e)
        {
            BindAllProducts();
        }

        // 添加到周报价商品
        protected void lbn_AddTo_Click(object sender, EventArgs e)
        {
            List<WeeklyProductItem> selectedProduct = null;
            if (!string.IsNullOrEmpty(hdProductSotre.Value))
            {
                selectedProduct = JsonConvert.DeserializeObject<List<WeeklyProductItem>>(hdProductSotre.Value);
            }
            else
            {
                selectedProduct = new List<WeeklyProductItem>();
            }

            foreach (RepeaterItem item in rpt_Products.Items)
            {
                if (item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.Item)
                {
                    CheckBox chk = item.FindControl("cbx_isSelect") as CheckBox;

                    if (chk != null && chk.Checked)
                    {
                        WeeklyProductItem product = new WeeklyProductItem();
                        product.ProductId = Convert.ToInt32(chk.Attributes["ProductId"]);
                        product.ProductName = chk.Attributes["ProductName"];
                        product.AvgSellerPrice = Convert.ToDecimal(chk.Attributes["AvgSellerPrice"]);
                        product.AutoAdd = Convert.ToDecimal(chk.Attributes["AutoAdd"]);
                        product.InitAutoAdd = Convert.ToDecimal(chk.Attributes["AutoAdd"]);
                        product.Price = Convert.ToDecimal(product.AvgSellerPrice * (1 + product.AutoAdd));

                        // 匿名方法查找
                        //ProductItem current = selectedProduct.Find(delegate(ProductItem productItem) { return productItem.ProductId == product.ProductId; });
                        // lamdba表达式
                        WeeklyProductItem current = selectedProduct.Find(productItem => productItem.ProductId == product.ProductId);
                        if (current == null)
                        {
                            selectedProduct.Add(product);
                        }
                    }
                }
            }

            if (selectedProduct != null)
            {
                hdProductSotre.Value = JsonConvert.SerializeObject(selectedProduct);
            }
            else
            {
                hdProductSotre.Value = string.Empty;
            }

            BindSelectedProduct();
        }

        // 绑定选择的商品
        private void BindSelectedProduct()
        {
            if (!string.IsNullOrEmpty(hdProductSotre.Value))
            {
                List<WeeklyProductItem> selectedProduct = JsonConvert.DeserializeObject<List<WeeklyProductItem>>(hdProductSotre.Value);
                rptSelectedProduct.DataSource = selectedProduct;
                rptSelectedProduct.DataBind();
            }
        }

        // 分页
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindAllProducts();
        }

        #endregion

        // 添加商品
        protected void lbn_AddProduct_Click(object sender, EventArgs e)
        {
            categoryRootBind();
            categorySubBind();
            BindAllProducts();

            win_product.Show();
        }

        protected void rptSelectedProduct_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            #region 删除选择的商品
            if (e.CommandName == "Del")
            {
                List<WeeklyProductItem> selectedProduct = null;
                if (!string.IsNullOrEmpty(hdProductSotre.Value))
                {
                    selectedProduct = JsonConvert.DeserializeObject<List<WeeklyProductItem>>(hdProductSotre.Value);
                    int productId = 0;
                    if (e.CommandArgument != null)
                    {
                        int.TryParse(e.CommandArgument.ToString(), out productId);
                    }

                    foreach (WeeklyProductItem item in selectedProduct)
                    {
                        if (item.ProductId == productId)
                        {
                            selectedProduct.Remove(item);
                            break;
                        }
                    }
                }

                if (selectedProduct != null)
                {
                    hdProductSotre.Value = JsonConvert.SerializeObject(selectedProduct);
                }
                else
                {
                    hdProductSotre.Value = string.Empty;
                }

                BindSelectedProduct();
            }
            #endregion
        }

        // 保存周报价商品
        protected void btnSaveWeeklyPrice_Click(object sender, EventArgs e)
        {
            #region 添加/编辑操作
            if (!string.IsNullOrEmpty(Request.QueryString["action"]))
            {
                if (rptSelectedProduct.Items.Count > 0)
                {
                    DataTable dt = new DataTable("buyerPrice");
                    dt.Columns.Add("bpwid", typeof(Int32));
                    dt.Columns.Add("productId", typeof(Int32));
                    dt.Columns.Add("avgSellerPrice", typeof(decimal));
                    dt.Columns.Add("priceRate", typeof(decimal));
                    dt.Columns.Add("enabledDeduct", typeof(bool));
                    dt.Columns.Add("initPriceRate",typeof(decimal));

                    HiddenField hhdProductId = null;
                    Literal lblAvgSellerPrice = null;
                    TextBox txtPriceRate = null;
                    HiddenField hdAutoAdd = null;
                    DataRow dr = null;

                    foreach (RepeaterItem item in rptSelectedProduct.Items)
                    {
                        if (item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.Item)
                        {
                            hhdProductId = item.FindControl("hdProductId") as HiddenField;
                            lblAvgSellerPrice = item.FindControl("lblAvgSellerPrice") as Literal;
                            txtPriceRate = item.FindControl("txtAutoAdd") as TextBox;
                            hdAutoAdd = item.FindControl("hdAutoAdd") as HiddenField;

                            dr = dt.NewRow();
                            dr[0] = bpwdid;
                            dr[1] = Convert.ToInt32(hhdProductId.Value);
                            dr[2] = Convert.ToDecimal(lblAvgSellerPrice.Text);
                            dr[3] = Convert.ToDecimal(txtPriceRate.Text);
                            dr[4] = Convert.ToBoolean(Convert.ToDecimal(txtPriceRate.Text) > Convert.ToDecimal(hdAutoAdd.Value));
                            dr[5] = Convert.ToDecimal(hdAutoAdd.Value);
                            dt.Rows.Add(dr);
                        }
                    }

                    if (Request.QueryString["action"] == "insert")
                    {
                        logic.buyerWeeklyPrice.bulkInsert(dt, bpwdid,1);
                        Library.Script.ClientMsg("保存成功.");
                        getDetails();
                    }
                    else if (Request.QueryString["action"] == "edit")
                    {
                        logic.buyerWeeklyPrice.bulkInsert(dt, bpwdid, 2);
                        Library.Script.ClientMsg("保存成功.");
                        getDetails();
                    }
                }
            }
            #endregion
        }

        // 审核
        protected void btnAudit_Click(object sender, EventArgs e)
        {
            if (hasPermission("KB",4))
            {
                // 1表示已提交;2表示已审核
                string status = "2";

                logic.purchaseWeek.updateStateByAudit(bpwdid,sysAdmin.AdminID,status);
                Library.Script.ClientMsg("审核成功.");
                getDetails();
            }
            else
            {
                Library.Script.ClientMsgUrl("当前用户没有权限！", "index.aspx");
                return;
            }
        }

        // 导出企业周报价
        protected void lbl_ExportToExcel_Click(object sender, EventArgs e)
        {
            // 查询数据
            DataTable dt = logic.buyerWeeklyPrice.listWithCompanyWeek(bpwdid);
            string title = string.Format("{0}({1}-{2})周报价单", lblWeek.Text, lblStartTime.Text, lblEndTime.Text);

            // 导出Excel
            ExportFacade exportInstance = new Facade.Excel.ExportFacade();
            Dictionary<int, FormatStyle> formatOptions = new Dictionary<int, FormatStyle>();

            exportInstance.ExportByWeb(dt, title, title + ".xls", formatOptions, title);
        }
    }

    internal class WeeklyProductItem
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public decimal AvgSellerPrice { get; set; }
        public decimal InitAutoAdd { get; set; }
        public decimal AutoAdd { get; set; }
        public decimal Price { get; set; }
    }
}
